package hello;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Mark
 * @date 2020/5/25 17:52
 * @description cookie和session
 */
public class SessionServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 解决乱码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        HttpSession session = req.getSession();
        session.setAttribute("name", "wang");
        String sessionId = session.getId();

        // 判断是否为最新session
        if (session.isNew()) {
            resp.getWriter().print("sessionId 创建成功" + sessionId);
        } else {
            resp.getWriter().print("sessionId 已经创建 sessionId为 = " + sessionId);
        }

        /*        // 实际上就是讲sessionId放入cookie里面进行对浏览器的访问
        Cookie cookie = new Cookie("JSESSIONID", sessionId);
        resp.addCookie(cookie);*/
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

}
